package com.zqh.thread;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;

public class ClientThread implements Runnable {

    private Selector selector;
    private int status;

    public ClientThread(Selector selector, int status) {
        this.selector = selector;
        this.status = status;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    @Override
    public void run() {

        try {

            while (true) {

                // 获取 channel 数量
                int channelNum = selector.select();

                // 如果没有获取到 channel 则退出当前循环
                if(channelNum == 0) {
                    continue;
                }

                // 获取可用的 channel
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                // 创建迭代器，遍历可用的 channel
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {

                    SelectionKey selectionKey = iterator.next(); // 获取 channel ，判断其状态

                    // 从集合中移除当前的 selectionKey (已经取出)
                    iterator.remove();

                    // 可读状态
                    if (selectionKey.isReadable()) {
                        readOperator(selector, selectionKey);
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 处理可读状态的操作（当服务端发送消息时）
    private void readOperator(Selector selector, SelectionKey selectionKey) throws IOException {

        // 从 selectionKey 中获取已经就绪的通道
        SocketChannel socketChannel = (SocketChannel)selectionKey.channel();

        // 创建 buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        // 读取服务端发送的消息
        int read = socketChannel.read(byteBuffer);
        String message = "";
        if (read > 0) {
            byteBuffer.flip(); // 切换读模式
            message += Charset.forName("UTF-8").decode(byteBuffer);
        }

        // 将 channel 再次注册到选择器上，继续监听可读状态
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 打印读取到的信息
        if (message.length() > 0) {
            System.out.println(message);
        }

    }

}
